/**
 * @Author: 魏巍
 * @Date:   2018-09-24T23:32:43+08:00
 * @Email:  524314430@qq.com
 * @Filename: app.js
 * @Last modified by:   魏巍
 * @Last modified time: 2018-09-26T02:44:09+08:00
 * @Copyright: free
 */

const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const nunjucks = require('koa-nunjucks-async')
const cors = require('@koa/cors')
const jwt = require('koa-jwt')
const jwksRsa = require('jwks-rsa')

const index = require('./routes/index')
const users = require('./routes/users')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
  .use(cors())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

const nunjucksOptions = {
  opts: {
    noCache: true,
    throwOnUndefined: false,
    watch: true
  },
  filters: {
    json: x => JSON.stringify(x, null, 2),
    ucfirst: e => typeof e === 'string' && e.toLowerCase() && e[0].toUpperCase() + e.slice(1)
  },
  globals: {
    title: 'My Page'
  },
  ext: '.nunjucks'
}

app.use(nunjucks(__dirname + '/views', nunjucksOptions))

// Middleware below this line is only reached if JWT token is valid
// unless the URL starts with '/public'
app.use(jwt({
  secret: jwksRsa.koaJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 2,
    jwksUri: `https://sandrino.auth0.com/.well-known/jwks.json`
  })
}).unless({
  path: [/^\/public/,/^\/index/]
}))

// Protected middleware
// app.use(function(ctx){
//   if (ctx.url.match(/^\/api/)) {
//     ctx.body = 'protected\n'
//   }
// })

app.use((ctx, next) => {
  return next().catch(err => {
    if (401 == err.status) {
      ctx.status = 401
      ctx.body = {
        error: err.originalError ? err.originalError.message : err.message,
        // error: 'Protected resource, use Authorization header to get access\n'
      }
    } else {
      throw err
    }
  })
})

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
